//
//  TabbarViewController.swift
//  ContactPoster
//
//  Created by TSYH on 2023/11/20.
//

import UIKit
import SnapKit

public protocol TabbarDelegate: NSObjectProtocol {
    func tabBar(_ tabbar: TabbarProtocol, didSelected index: Int)
}

public protocol TabbarProtocol where Self: UIView {
    var delegate: TabbarDelegate? { get set }
    func tabBar(_ tabController: TabbarViewController, didSelected index: Int)
}

public protocol TabbarViewControllerDataSource {
    func tabbar(for tabController: TabbarViewController) -> TabbarProtocol
    
    func childViewContollers(_ tabController: TabbarViewController) -> [UIViewController]
    
    func childViewContoller(_ tabController: TabbarViewController, at index: Int) -> UIViewController
}

open class TabbarViewController: UITabBarController {
    var dataSource: TabbarViewControllerDataSource
    
    public required init(dataSource: TabbarViewControllerDataSource) {
        self.dataSource = dataSource
        super.init(nibName: nil, bundle: nil)
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var customTabbar: TabbarProtocol {
        return dataSource.tabbar(for: self)
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        let childVCs = dataSource.childViewContollers(self)
        childVCs.forEach { vc in
            addChild(vc)
        }
        
        // 自定义tabbar
        customTabbar.delegate = self
        self.tabBar.addSubview(customTabbar)
        customTabbar.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
        }
    }
    
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        tabBar.bringSubviewToFront(customTabbar)
    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 移除默认TabBarItem
        tabBar.subviews.forEach { subview in
            if subview is UIControl {
                subview.isUserInteractionEnabled = false
            }
        }
    }
    
    open override var selectedIndex: Int {
        didSet {
            dataSource.tabbar(for: self).tabBar(self, didSelected: selectedIndex)
        }
    }
    
    open func tabBarDidSelected(at index: Int, from previousIndex: Int) {}
}

extension TabbarViewController: TabbarDelegate {
    public func tabBar(_ tabbar: TabbarProtocol, didSelected index: Int) {
        let previousIndex = selectedIndex
        self.selectedIndex = index
        tabBarDidSelected(at: index, from: previousIndex)
    }
}
